/**
 * 2019年2月19日上午7:08:26
 * @author 谢进财
 */
package com.baihang.project.ds.service;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.util.TypeUtils;
import com.baihang.framework.kit.ShiroKit;
import com.baihang.framework.kit.StrKit;
import com.baihang.framework.kit.database.RedisKit;
import com.baihang.framework.service.BaseService;
import com.baihang.project.ds.entity.ShouCangEntity;
import com.baihang.project.ds.model.FangYuanModel;

import redis.clients.jedis.Jedis;

/**
 * @author whati
 *
 */
@Service
public class ShouCangRedisService extends BaseService {
	private static Logger logger = LoggerFactory.getLogger(ShouCangRedisService.class);
	private Jedis jedis = RedisKit.getJedis();

	// 主要操作 userShouCang 这个redis map
	public String doShouCang(int id) {
		logger.info("开始redis收藏操作");
		String scJson = "";
		if (jedis.hexists("userShouCang", ShiroKit.getCurrentUser().getUserName())) {
			// 是否有收藏
			scJson = jedis.hmget("userShouCang", ShiroKit.getCurrentUser().getUserName()).get(0);
			if (StrKit.isNotEmpty(scJson)) {
				if (scJson.contains(String.valueOf(id))) {
					return "您已经收藏过";
				}
				String[] sc = scJson.split(",");
				// 收藏是否达上限
				if (sc.length >= Integer.valueOf(jedis.hmget("systemConfig", "CollectionCount").get(0))) {
					return "您已达收藏上限";
				}
			}
		}

		// 用户收藏加入此房源id
		if(StrKit.isNotEmpty(scJson)){
			scJson += "," + String.valueOf(id);
		}else {
			scJson += String.valueOf(id);
		}
		jedis.hset("userShouCang", ShiroKit.getCurrentUser().getUserName(), scJson);
		// 房源中增加收藏数
		String modelJson = jedis.hmget("rooms", String.valueOf(id)).get(0);
		FangYuanModel model = JSON.parseObject(modelJson, new TypeReference<FangYuanModel>() {
		});
		int cc = model.getE_CollectionCount() + 1;
		model.setE_CollectionCount(cc);
		TypeUtils.compatibleWithFieldName = true;
		jedis.hset("rooms", String.valueOf(id), JSON.toJSONString(model));
		return "收藏成功";
	}

	// 计算剩余可以收藏房源
	public int countSyShouCang() {
		int num = 0;
		if (jedis.hexists("userShouCang", ShiroKit.getCurrentUser().getUserName())) {
			// 是否有收藏
			String scJson = jedis.hmget("userShouCang", ShiroKit.getCurrentUser().getUserName()).get(0);
			if (StrKit.isNotEmpty(scJson)) {
				String[] sc = scJson.split(",");
				num = sc.length;
			}
		}

		int syNum = Integer.valueOf(jedis.hmget("systemConfig", "CollectionCount").get(0)) - num;
		return syNum;
	}

	// 获取当前用户收藏的房源
	public List<ShouCangEntity> getShouCang() {
		List<ShouCangEntity> list = new ArrayList<ShouCangEntity>();
		if (jedis.hexists("userShouCang", ShiroKit.getCurrentUser().getUserName())) {
			// 是否有收藏
			String scJson = jedis.hmget("userShouCang", ShiroKit.getCurrentUser().getUserName()).get(0);
			logger.info("当前用户收藏="+scJson);
			if (StrKit.isNotEmpty(scJson)) {
				String[] sc = scJson.split(",");
				for (int i = 0; i < sc.length; i++) {
					String modelJson = jedis.hmget("rooms", sc[i]).get(0);
					ShouCangEntity model = JSON.parseObject(modelJson, new TypeReference<ShouCangEntity>() {
					});
					model.setSort(i + 1);
					list.add(model);
				}
			} else {
				list = null;
			}
		} else {
			list = null;
		}
		return list;
	}

	// 向上移 本质是两个位置的值互换
	public boolean doTop(int id, int sort) {
		String scJson = jedis.hmget("userShouCang", ShiroKit.getCurrentUser().getUserName()).get(0);
		String[] sc = scJson.split(",");
		String dqData = sc[sort - 1];// 选中的数据库，数组索引从0开始，界面是从1开始
		// 上一条数据排序下划一位
		sc[sort - 1] = sc[sort - 2];// 将本条的位置赋值上一条数值
		// 上升
		sc[sort - 2] = dqData;

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < sc.length; i++) {
			sb.append(sc[i] + ",");
		}
		sb.delete(sb.length() - 1, sb.length());
		jedis.hset("userShouCang", ShiroKit.getCurrentUser().getUserName(), sb.toString());
		return true;
	}

	// 向下移
	public boolean doDown(int id, int sort) {
		String scJson = jedis.hmget("userShouCang", ShiroKit.getCurrentUser().getUserName()).get(0);
		String[] sc = scJson.split(",");
		String dqData = sc[sort - 1];// 选中的数据库，数组索引从0开始，界面是从1开始
		// 下一条数据排序上移一位
		sc[sort - 1] = sc[sort];// 将本条的位置赋值上一条数值
		// 下降
		sc[sort] = dqData;

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < sc.length; i++) {
			sb.append(sc[i] + ",");
		}
		sb.delete(sb.length() - 1, sb.length());
		jedis.hset("userShouCang", ShiroKit.getCurrentUser().getUserName(), sb.toString());
		return true;
	}

	// 删除
	public boolean doDel(int fangyuanId, int sort) {
		logger.info(String.format("%s想删除序号为%d的房源", ShiroKit.getCurrentUser().getUserName(),sort));
		String scJson = jedis.hmget("userShouCang", ShiroKit.getCurrentUser().getUserName()).get(0);
		if(scJson.contains(",")) {
			String[] sc = scJson.split(",");
			String[] newSc = deleteSc(sort - 1, sc);// 删除指定序号的收藏
			// 回填收藏
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < newSc.length; i++) {
				sb.append(newSc[i] + ",");
			}
			sb.delete(sb.length() - 1, sb.length());
			jedis.hset("userShouCang", ShiroKit.getCurrentUser().getUserName(), sb.toString());
		}else {
			jedis.hset("userShouCang", ShiroKit.getCurrentUser().getUserName(), "");
		}
		// 修改房源收藏数据

		String modelJson = jedis.hmget("rooms", String.valueOf(fangyuanId)).get(0);
		FangYuanModel model = JSON.parseObject(modelJson, new TypeReference<FangYuanModel>() {});
		int cc = model.getE_CollectionCount() - 1;
		model.setE_CollectionCount(cc);
		TypeUtils.compatibleWithFieldName = true;
		jedis.hset("rooms", String.valueOf(fangyuanId), JSON.toJSONString(model));
		
		return true;
	}

	// 数组删除帮助方法
	public String[] deleteSc(int index, String array[]) {
		// 数组的删除其实就是覆盖前一位
		String[] arrNew = new String[array.length - 1];
		for (int i = 0; i < arrNew.length ; i++) {
			if (i < index) {
				arrNew[i] = array[i];
			} else {
				arrNew[i] = array[i + 1];
			}
		}
		return arrNew;
	}
	
	public static void main(String[] args) {
		ShouCangRedisService service = new ShouCangRedisService();
		Jedis jedis = RedisKit.getJedis();
		String scJson = jedis.hmget("userShouCang", "15858830597").get(0);
		System.err.println(scJson);
		if(scJson.contains(",")) {
			String[] sc = scJson.split(",");
			String[] newSc = service.deleteSc(0, sc);// 删除指定序号的收
			System.err.println(newSc.length);
		}
	}
	
	
}
